const querystring = require('querystring');
const http = require('http');
const fs = require('fs');

function upload() {
    let boundaryKey = '----' + new Date().getTime(); // 用于标识请求数据段
    const options = {
        hostname: 'localhost',
        port: 2200,
        path: '/Upload/',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data; boundary=' + boundaryKey,
            'Connection': 'keep-alive'
        }
    };

    const req = http.request(options, (res) => {
        console.log(`STATUS: ${res.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`);

        });
        res.on('end', () => {
            console.log('No more data in response.');
        });
    });

    req.on('error', (e) => {
        console.error(111, e);
        console.error(`problem with request1: ${e.message}`);
    });

    // Write data to request body
    // req.write(postData);
    req.write(
        boundaryKey + 'rn' +
        'Content-Disposition: form-data; name="file"; filename="file.path.txt"rn' +
        'Content-Type: text/plain' + 
        boundaryKey + '--'
    );
    req.end();

    let fileStream = fs.createReadStream('./txt/file.path.txt');
    fileStream.pipe(req, {
        end: false
    });
    fileStream.on('end', function () {
        req.end('rn--' + boundaryKey + '--');
        callback && callback(null);
    });
}
upload()